<template>
  <div class="jax-form-group">
    <template v-for="(item, index) in formItemList" :key="item.itemProps.name || index">
      <template v-if="$slots[item.itemProps.name]">
        <slot :name="item.itemProps.name" :item="item"></slot>
      </template>
      <FormItem
        v-else
        v-model="modelValue[item.itemProps.name]"
        :type="item.type"
        :item-props="item.itemProps"
        :input-props="item.inputProps"
        class="jax-form-item"
      >
        <template #input v-if="$slots[item.itemProps.name + '-input']">
          <slot :name="item.itemProps.name + '-input'" :item="item"></slot>
        </template>
      </FormItem>
    </template>
  </div>
</template>
<script setup>
import { rule } from 'postcss'
import FormItem from './FormItem.vue'

const props = defineProps({
  modelValue: { type: Object, default: () => {} },
  json: {
    type: Array,
    default: [],
  },
})

const formItemList = computed(() => {
  return props.json.map(itemOptions => {
    const type = itemOptions.type || 'text'

    const itemProps = getFormItemProps(type, itemOptions)
    const inputProps = getInputProps(type, itemOptions)

    return {
      type,
      itemProps,
      inputProps,
    }
  })
})

function getFormItemProps(type, options) {
  const required = options.required
  let rules = []

  switch (type) {
    case 'text':
      if (!options.placeholder) options.placeholder = `请输入${options.label}`
      if (required) rules = [{ required: true, errorMessage: `请输入${options.label}` }]
      break
    case 'radio':
      if (required) rules = [{ required: true, errorMessage: `请选择${options.label}` }]
      break
    case 'select':
      if (!options.placeholder) options.placeholder = `请选择${options.label}`
      if (required) rules = [{ required: true, errorMessage: `请选择${options.label}` }]
      if (options.options) break
    default:
      break
  }

  if (options.rules) {
    rules = [...rules, ...options.rules]
  }

  return {
    name: options.name,
    required: options.required,
    label: options.label,
    rules,
  }
}

function getInputProps(type, itemOptions) {
  let options = []
  let placeholder

  if (['radio', 'checkbox', 'select'].includes(type)) {
    options = itemOptions?.options.map(item => {
      return {
        text: item.label,
        value: item.value,
      }
    })
  }

  if (type == 'data-picker') options = itemOptions?.options

  if (!itemOptions.placeholder) {
    if (['data-picker', 'select'].includes(type)) {
      placeholder = `请选择${itemOptions.label}`
    } else {
      placeholder = `请输入${itemOptions.label}`
    }
  }

  return {
    options,
    placeholder,
  }
}
</script>
<style lang="scss" scoped></style>
